/*
自定义路由
*/
const express = require("express");
const fs = require("fs");
const multer = require("multer");
// 导入 jsonwebtoken
const jsonwebtoken = require("jsonwebtoken");
// 导入 express-jwt
const { expressjwt } = require("express-jwt");

const router = express.Router();

const up = multer({
  // 配置存放目录
  dest: "./public/uploads",
});
// 告诉服务器，传输文件字段名
router.use(up.single("file"));

// 导入数据库
const db = require("./db.json");

// 每次请求检查是否携带凭证
// Bearer eqweqddfsdfsf
const checkToken = expressjwt({
  secret: "abc123",
  algorithms: ["HS256"],
}).unless({
  path: ["/login", "/db", "/favicon.ico"],
});
// router.use(checkToken);
/*
  POST /login
  {"username":"...","password":"...."}
*/
router.post("/login", (req, res) => {
  const { username, password } = req.body;
  const index = db.users.findIndex(
    (el) => el.username === username && el.password === password
  );
  // 签名 （内容，密钥，过期时间）
  const token = jsonwebtoken.sign({ username }, "abc123", {
    expiresIn: 3600 * 24 * 3, //过期时间
  });
  res.send(
    index === -1
      ? { error: 4001, msg: "用户名或密码错误" }
      : { error: 0, data: "Bearer " + token }
  );
});

router.get("/xml", (req, res) => {
  res.type("xml");
  res.send(`
    <user>
      <name>jack</name>
      <age>20</age>
      <gender>boy</gender>
    </user>
  `);
});
router.get("/video", (req, res) => {
  res.sendFile("f:/video/9-1.错误处理5.mp4");
});

router.get("/img", (req, res) => {
  res.sendFile("F:/code-209/mock-server/public/code.jpg");
});

router.post("/upload", (req, res) => {
  // 获取文件后缀名
  const ext = req.file.originalname.split(".").slice(-1)[0];
  // 新的加了后缀名的path
  const newPath = `${req.file.path}.${ext}`;
  // 重命名文件
  fs.rename(req.file.path, newPath, (err) => {
    console.log(err);
  });
  res.send({ error: 0, msg: "图片上传成功" });
});
module.exports = router;
